import { Button, message, Modal, Tooltip, Upload } from "antd";
import { useEffect, useRef, useState } from "react";
import Divider from "~/components/ui/divider";
import type { INovel, INovelChapter } from "~/types/manage/content/novel";

import Editor from "@monaco-editor/react";
import type { RcFile } from "antd/es/upload";
import { CoinsIcon } from "lucide-react";
import type { editor } from "monaco-editor";
import { apiModifyNovelChapters, apiNovelChapters } from "~/api/novel";
import {
  cn,
  countWords,
  isChapterExtra,
  isChapterTitle,
} from "~/utils/ui.util";

interface Props {
  visible: boolean;
  novelRecord: INovel | null;
  onCancel: () => void;
  onOk: () => void;
}

interface IChapterTitle {
  id?: number;
  title: string;
  line: number;
  charge: boolean;
  contentLength: number;
}

export default function NovelChapterModal(props: Props) {
  const [chapterTitleList, setChapterTitleList] = useState<IChapterTitle[]>([]);
  const [chapterContentList, setChapterContentList] = useState<string[]>([]);
  const [novelContent, setNovelContent] = useState("");
  const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
  const [indexChapterIdMap, setIndexChapterIdMap] =
    useState<Map<number, number>>();
  const [chargeIndexConfig, setChargeIndexConfig] = useState<{
    chargeIndex: number;
    charge: boolean;
  }>();
  // 总字数
  const [totalWords, setTotalWords] = useState<number>();
  // 收费字数
  const [chargeWords, setChargeWords] = useState<number>();
  // 收费章节数
  const [chargeChapters, setChargeChapters] = useState<number>();

  const _handler = {
    onBeforeUpload: (file: RcFile) => {
      const reader = new FileReader();
      reader.readAsText(file, "utf-8");
      reader.onload = () => {
        _handler.onEditorChange(reader.result as string);
      };
    },
    onEditorMounted: (editor: editor.IStandaloneCodeEditor, monaco: any) => {
      editorRef.current = editor;
      editor.updateOptions({
        wordWrap: "on",
      });
    },
    onEditorChange: (value: string | undefined) => {
      // 解析章节内容
      const tempChapterTitleList: IChapterTitle[] = [];
      const tempChapterContentList: string[] = [];
      const lines = value?.split("\n") || [];
      const tempContent: string[] = [];

      tempChapterTitleList.push({
        line: 0,
        title: "导语",
        charge:
          chargeIndexConfig?.chargeIndex !== undefined &&
          0 >= chargeIndexConfig.chargeIndex,
        contentLength: 0,
      });

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (isChapterTitle(line) || isChapterExtra(line)) {
          const index = tempChapterTitleList.length;
          tempChapterTitleList.push({
            line: i + 1,
            title: line,
            charge:
              chargeIndexConfig?.chargeIndex !== undefined &&
              index > chargeIndexConfig.chargeIndex,
            contentLength: 0,
          });
          const content = tempContent.join("\n");
          tempChapterContentList.push(content);
          tempChapterTitleList[tempChapterTitleList.length - 2].contentLength =
            countWords(content);
          tempContent.length = 0;
        } else {
          tempContent.push(line);
        }
      }
      const content = tempContent.join("\n");
      tempChapterContentList.push(content);
      tempChapterTitleList[tempChapterTitleList.length - 1].contentLength =
        countWords(content);
      setChapterTitleList(tempChapterTitleList);
      setChapterContentList(tempChapterContentList);
      setNovelContent(value || "");
    },
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      try {
        message.info("章节更新中...");
        await _fetch.modifyNovelChapters(props.novelRecord?.id || 0, {
          novel: {
            totalWords,
            chargeWords,
            totalChapters: chapterTitleList.length,
            chargeChapters,
          },
          chapters: chapterTitleList.map((item, index) => ({
            id: indexChapterIdMap?.get(index),
            novelId: props.novelRecord?.id,
            index: index + 1,
            title: item.title,
            content: chapterContentList[index],
            length: item.contentLength,
            charge: item.charge,
            line: item.line,
          })),
        });
        message.success("章节更新成功");
        props.onOk?.();
      } catch (error: any) {
        message.error(`章节更新失败: ${error.message}`);
      }
    },
    // 添加章节点击处理函数
    handleChapterClick: (item: { line: number; title: string }) => {
      if (editorRef.current) {
        // 这里假设章节索引与行号对应关系，实际应根据内容解析结果调整
        editorRef.current.revealLineInCenter(item.line);
        editorRef.current.setSelection({
          startLineNumber: item.line,
          startColumn: 1,
          endLineNumber: item.line + 1,
          endColumn: 1,
        });
      }
    },
    // 切换章节收费状态
    handleChargeClick: (chargeIndex: number, charge: boolean) => {
      setChargeIndexConfig({
        chargeIndex,
        charge,
      });
    },
  };

  const _fetch = {
    modifyNovelChapters: async (
      novelId: number,
      data: {
        novel: Partial<INovel>;
        chapters: Partial<INovelChapter>[];
      },
    ) => {
      await apiModifyNovelChapters(novelId, data);
    },
    novelChapter: async (novelId: number) => {
      const res = await apiNovelChapters(novelId);
      const content = res
        .map((item) => {
          if (item.title === "导语") {
            return `${item.content}`;
          }
          return `${item.title}\n${item.content}`;
        })
        .join("\n");
      setChapterTitleList(
        res.map((item) => {
          return {
            title: item.title,
            line: item.line,
            charge: item.charge,
            contentLength: item.length,
          };
        }),
      );
      setNovelContent(content);
      setChapterContentList(res.map((item) => item.content));
      setIndexChapterIdMap(new Map(res.map((item, index) => [index, item.id])));
      setChargeIndexConfig({
        chargeIndex:
          (props.novelRecord?.totalChapters || 0) -
          (props.novelRecord?.chargeChapters || 0) -
          1,
        charge: false,
      });
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    // 初始化
    setNovelContent("");
    setChapterTitleList([]);
    setChapterContentList([]);

    // 加载数据
    if (props.novelRecord) {
      _fetch.novelChapter(props.novelRecord.id);
      // 设置 收费章节等
      // setTotalWords(props.novelRecord.totalWords);
      // setChargeWords(props.novelRecord.chargeWords);
      // setTotalChapters(props.novelRecord.totalChapters);
      // setChargeChapters(props.novelRecord.chargeChapters);
    }
  }, [props.visible, props.novelRecord]);

  useEffect(() => {
    if (chapterTitleList.length === 0) {
      return;
    }
    let totalWords = 0;
    let chargeWords = 0;
    let totalChapters = 0;
    let chargeChapters = 0;
    chapterTitleList.forEach((item) => {
      totalWords += item.contentLength;
      if (item.charge) {
        chargeWords += item.contentLength;
        chargeChapters++;
      }
      totalChapters++;
    });
    setTotalWords(totalWords);
    setChargeWords(chargeWords);
    setChargeChapters(chargeChapters);
  }, [chapterTitleList]);

  useEffect(() => {
    if (chargeIndexConfig?.chargeIndex === undefined) {
      return;
    }
    const tempChapterTitleList = [...chapterTitleList];
    tempChapterTitleList.forEach((item, index) => {
      if (index === chargeIndexConfig.chargeIndex) {
        item.charge = chargeIndexConfig.charge;
      } else if (index < chargeIndexConfig.chargeIndex) {
        item.charge = false;
      } else {
        item.charge = true;
      }
    });
    setChapterTitleList(tempChapterTitleList);
  }, [chargeIndexConfig]);

  return (
    <Modal
      title={"内容章节"}
      open={props.visible}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
      maskClosable={false}
      width={1200}
    >
      <div className="flex h-[70vh] flex-col gap-2 overflow-hidden">
        <div className="flex items-center gap-2">
          <span className="text-gray-500">标题:</span>
          <span className="text-xl font-bold">
            {props.novelRecord?.title || "--"}
          </span>
        </div>
        <div className="flex items-center gap-2">
          <div className="flex gap-2">
            <span className="text-gray-500">作者:</span>
            <span className="font-bold">
              {props.novelRecord?.penName || "--"}
            </span>
          </div>
          {/* <div className="flex gap-2">
            <span className="text-gray-500">邮箱:</span>
            <span className="font-bold">
              {props.novelRecord?.email || "--"}
            </span>
          </div> */}
        </div>
        <div className="flex flex-1 gap-2 overflow-hidden">
          <div className="flex h-full w-[140px] flex-col gap-2">
            <span className="text-gray-500">章节列表</span>
            <div className="h-full w-full overflow-auto bg-gray-100">
              {chapterTitleList.map((item, index) => {
                return (
                  <div
                    className="group/item cursor-pointer rounded p-2 hover:bg-gray-200"
                    key={index}
                    onClick={() => _handler.handleChapterClick(item)}
                  >
                    <div className="flex justify-between">
                      <span>{item.title}</span>
                      <div
                        className={cn({
                          "invisible text-gray-500 group-hover/item:visible":
                            !item.charge,
                        })}
                      >
                        <Tooltip
                          title={
                            item.charge
                              ? "此章及之前取消收费"
                              : "此章及之后开始收费"
                          }
                        >
                          <CoinsIcon
                            size={18}
                            className={cn({
                              "hover:text-gray-700": !item.charge,
                              "text-yellow-400": item.charge,
                            })}
                            onClick={(e) => {
                              _handler.handleChargeClick(index, !item.charge);
                              e.stopPropagation();
                            }}
                          />
                        </Tooltip>
                      </div>
                    </div>
                    <span className="text-sm text-gray-400">
                      字数: {item.contentLength}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
          <Divider />
          <div className="flex h-full flex-1 flex-col gap-2">
            <div className="flex items-center justify-between">
              <div className="flex-1">
                <Upload
                  showUploadList={false}
                  customRequest={() => {}}
                  beforeUpload={_handler.onBeforeUpload}
                >
                  <Button>导入</Button>
                </Upload>
              </div>

              <div className="grid flex-2/3 grid-cols-4">
                <div className="flex gap-1">
                  <span className="text-gray-400">总章节:</span>
                  <span className="text-xl font-bold">
                    {chapterTitleList.length}
                  </span>
                </div>
                <div className="flex gap-1">
                  <span className="text-gray-400">收费章节:</span>
                  <span className="text-xl font-bold">{chargeChapters}</span>
                </div>
                <div className="flex gap-1">
                  <span className="text-gray-400">总字数:</span>
                  <span className="text-xl font-bold">{totalWords}</span>
                </div>
                <div className="flex gap-1">
                  <span className="text-gray-400">收费字数:</span>
                  <span className="text-xl font-bold">{chargeWords}</span>
                </div>
              </div>
            </div>
            <div className="flex flex-1 border border-gray-300">
              <Editor
                className="h-full w-full"
                options={{
                  fontSize: 14,
                  minimap: { enabled: false }, // 可选：关闭小地图
                  scrollBeyondLastLine: false, // 可选：禁止滚动到最后一行的下方
                }}
                onMount={_handler.onEditorMounted}
                onChange={_handler.onEditorChange}
                defaultLanguage="text"
                value={novelContent}
              />
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
}
